import { Component, Children, cloneElement, ReactNode, ReactElement } from 'react'

class Parent extends Component {
    state = {
        count: 1
    }
    handleClick = () => {
        this.setState({
            count: this.state.count + 1
        })
    }
    /**
     * 1、React.Children 提供了用于处理 this.props.children 不透明数据结构的实用方法
     * 2、React.Children: {map: ƒ, forEach: ƒ, count: ƒ, toArray: ƒ, only: ƒ}
     * 3、this.props.chiddren 是一个react element
     */
    getChildren = () => {
        const { children } = this.props
        console.log(Children.count(children), 'count of children') // 可以获取子元素的数量
        console.log(Children.toArray(children), 'toArray')

        // 1、推荐写法
        return Children.map(children, (child: ReactNode) => cloneElement((child as ReactElement), { count: this.state.count }))

        // 2、为什么这样不可以？
        // cloneElement((this.props.children as any), this.state.count)

        // 3、toArray
        // return Children.toArray(children).map(child => cloneElement((child as any), { count: this.state.count }))
    }
    render() {
        return (
            <div>
                <button onClick={this.handleClick} >add</button>
                {this.getChildren()}
            </div>
        )
    }
}

class Child extends Component<{ count?: number }> {
    render() {
        return (
            <div>
                This is child component: {this.props.count}
            </div>
        )
    }
}

class CloneTest extends Component {
    render() {
        return (
            <Parent>
                <Child />
            </Parent>
        )
    }
}

export default CloneTest